<template>
  <a-spin :spinning="confirmLoading">
    <JFormContainer :disabled="disabled">
      <template #detail>
        <a-form ref="formRef" class="antd-modal-form" :labelCol="labelCol" :wrapperCol="wrapperCol" name="CSubProjectForm">
          <a-row>
						<a-col :span="12">
							<a-form-item label="主项目" v-bind="validateInfos.projectId" id="CSubProjectForm-projectId" name="projectId">
								 <j-dict-select-tag showSearch="true"   :disabled="projectDisabled"  v-model:value="formData.projectId" dictCode="c_project_application,project_name,id" placeholder="请输入主项目"  allow-clear />
							</a-form-item>
						
						</a-col>
						<a-col :span="12">
							<a-form-item label="子项目名称" v-bind="validateInfos.subProjectName" id="CSubProjectForm-subProjectName" name="subProjectName">
								<a-input v-model:value="formData.subProjectName" placeholder="请输入子项目名称"  allow-clear ></a-input>
							</a-form-item>
						</a-col>
						<a-col :span="12">
							<a-form-item label="子项目描述" v-bind="validateInfos.subProjectDescription" id="CSubProjectForm-subProjectDescription" name="subProjectDescription">
								<a-textarea v-model:value="formData.subProjectDescription" :rows="4" placeholder="请输入子项目描述" />
							</a-form-item>
						</a-col>
						<a-col :span="12">
							<a-form-item label="工程详细地址" v-bind="validateInfos.address" id="CProjectApplicationForm-address" name="address">
								<a-textarea v-model:value="formData.address" :rows="4" placeholder="请输入工程详细地址" />
							</a-form-item>
						</a-col>
						<a-col :span="12">
							<a-form-item label="指派给分包商" v-bind="validateInfos.contactId" id="CSubProjectForm-contactId" name="contactId">
								 <j-dict-select-tag showSearch="true"   v-model:value="formData.contactId" dictCode="c_contractor_info,contact_name,id" placeholder="请输入分包商"  allow-clear />
							</a-form-item>
						</a-col>
            <a-col :span="12" v-show="formData.additionalId">
              <a-form-item label="项目需求" v-bind="validateInfos.additionalId" id="CSubProjectForm-additionalId" name="additionalId">
                <j-dict-select-tag showSearch="true"  disabled="true"  v-model:value="formData.additionalId" dictCode="c_additional_request,title,id" placeholder="请输入项目需求"  allow-clear />
              </a-form-item>
            </a-col>

            <a-col :span="12" >
              <a-form-item label="子项目编号" v-bind="validateInfos.projectNumber" id="CSubProjectForm-projectNumber" name="projectNumber">
                <a-input v-model:value="formData.projectNumber"  placeholder="请输入子项目编号"  allow-clear ></a-input>
              </a-form-item>
            </a-col>


            <a-col :span="12">
							<a-form-item label="预算（不含税）"  v-bind="validateInfos.budget" id="CSubProjectForm-budget" name="budget">
                <a-input-number v-model:value="formData.budget" placeholder="请输入子项目预算（不含税）" style="width: 80%" />
							</a-form-item>
						</a-col>

						<a-col :span="12">
							<a-form-item label="合同文件" v-bind="validateInfos.fileRecordId" id="CSubProjectForm-fileRecordId" name="fileRecordId">
								<j-upload v-model:value="formData.fileRecordId" dragger="true"   :show-upload-list="{ showDownloadIcon: true, showRemoveIcon: true }" ></j-upload>
							</a-form-item>
						</a-col>
						<a-col :span="12">
							<a-form-item label="附件" v-bind="validateInfos.attachmentUrl" id="CProjectApplicationForm-attachmentUrl" name="attachmentUrl">
								<j-upload v-model:value="formData.attachmentUrl"  dragger="true"  :show-upload-list="{ showDownloadIcon: true, showRemoveIcon: true }"  text="上传"></j-upload>
								 
							</a-form-item>
						</a-col>
          </a-row>
        </a-form>
      </template>
    </JFormContainer>
  </a-spin>
</template>

<script lang="ts" setup>
  import { ref, reactive, defineExpose, nextTick, defineProps, computed, onMounted } from 'vue';
  import { defHttp } from '/@/utils/http/axios';
  import JDictSelectTag from '/@/components/Form/src/jeecg/components/JDictSelectTag.vue';
  import JUpload from '/@/components/Form/src/jeecg/components/JUpload/JUpload.vue';
  import JImageUpload from '/@/components/Form/src/jeecg/components/JImageUpload.vue';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { getValueType } from '/@/utils';
  import { saveOrUpdate } from '../CSubProject.api';
  import { Form } from 'ant-design-vue';
  import JFormContainer from '/@/components/Form/src/container/JFormContainer.vue';
  import { getQueryByProjectId } from '@/views/common.api';
  const props = defineProps({
    formDisabled: { type: Boolean, default: false },
    formData: { type: Object, default: () => ({})},
    formBpm: { type: Boolean, default: true }
  });
  const formRef = ref();
  const projectDisabled = ref(true);
  const useForm = Form.useForm;
  const emit = defineEmits(['register', 'ok']);
  const formData = reactive<Record<string, any>>({
    id: '',
    projectId: '',   
    subProjectName: '',   
    subProjectDescription: '',   
    contactId: '',   
    status: '',
    additionalId:'',
    startDate: '',   
    endDate: '',   
    budget: undefined,
    fileRecordId: '',
    projectNumber:'',
    attachmentUrl:'',
    totalQuotation: undefined,
  });
  const { createMessage } = useMessage();
  //const tooltipTitle = ref();
  const labelCol = ref<any>({ xs: { span: 24 }, sm: { span: 5 } });
  const wrapperCol = ref<any>({ xs: { span: 24 }, sm: { span: 16 } });
  const confirmLoading = ref<boolean>(false);
  //表单验证
  const validatorRules = reactive({
    projectId: [{ required: true, message: '请输入主项目!'},],
    subProjectName: [{ required: true, message: '请输入子项目名称!'},],
	contactId: [{ required: true, message: '请输入分包商'},],
	budget: [{ required: true, message: '请输入预算!'},],
  });
  const { resetFields, validate, validateInfos } = useForm(formData, validatorRules, { immediate: false });

  // 表单禁用
  const disabled = computed(()=>{
    if(props.formBpm === true){
      if(props.formData.disabled === false){
        return false;
      }else{
        return true;
      }
    }
    return props.formDisabled;
  });

  
  /**
   * 新增
   */
  function add(record) {
	  formData.projectId=record['id']
	  formData.subProjectDescription=record['projectDescription']
	  formData.address=record['address']
	  formData.contactId=''
    formData.projectNumber = ''
    formData.attachmentUrl=''
    formData.budget=''
    formData.additionalId=''
    formData.fileRecordId=''
    formData.subProjectName=record.subProjectName
   // tooltipTitle.value = "333";
    //通过库 带出项目地址
    if(record['id']){
      queryByProjectId(record['id'])
    }
    if(record.additionalId){
      projectDisabled.value=false;
    }
	//edit(record)
  }

  function addSubProject(record) {

    formData.subProjectDescription=record['subProjectDescription']
    formData.address=record['address']
    formData.attachmentUrl=record.attachmentUrl
    formData.budget=''
    formData.fileRecordId=''
    formData.subProjectName=record.subProjectName
    formData.projectNumber=record.projectNumber
    formData.projectId=record.projectId
    formData.additionalId=record.additionalId

    // tooltipTitle.value = "333";
    //通过库 带出项目地址
    if(record['id']){
      queryByProjectId(record['id'])
    }
    if(record.additionalId){
      projectDisabled.value=false;
    }
    //edit(record)
  }

  /**
   * 编辑
   */
  function edit(record) {
    nextTick(() => {
      resetFields();
      const tmpData = {};
      Object.keys(formData).forEach((key) => {
        if(record.hasOwnProperty(key)){
          tmpData[key] = record[key]
        }
      })
      //赋值
      Object.assign(formData, tmpData);
    });
  }

  /**
   * 查询项目库地址
   * @param id
   */
  async function queryByProjectId(id){
    const param = {"projectId":id}
    const data =  await getQueryByProjectId(param)
    let address =""
    if(data.city){
      address += data.city
    }
    if(address){
      address +="-"
    }
    if(data.address){
      address += data.address
    }
    formData.address = address
  }

  /**
   * 提交数据
   */
  async function submitForm() {
    try {
      // 触发表单验证
      await validate();
    } catch ({ errorFields }) {
      if (errorFields) {
        const firstField = errorFields[0];
        if (firstField) {
          formRef.value.scrollToField(firstField.name, { behavior: 'smooth', block: 'center' });
        }
      }
      return Promise.reject(errorFields);
    }
    confirmLoading.value = true;
    const isUpdate = ref<boolean>(false);
    //时间格式化
    let model = formData;
    if (model.id) {
      isUpdate.value = true;
    }
    //循环数据
    for (let data in model) {
      //如果该数据是数组并且是字符串类型
      if (model[data] instanceof Array) {
        let valueType = getValueType(formRef.value.getProps, data);
        //如果是字符串类型的需要变成以逗号分割的字符串
        if (valueType === 'string') {
          model[data] = model[data].join(',');
        }
      }
    }
    await saveOrUpdate(model, isUpdate.value)
      .then((res) => {
        if (res.success) {
          createMessage.success(res.message);
          emit('ok');
        } else {
          createMessage.warning(res.message);
        }
      })
      .finally(() => {
        confirmLoading.value = false;
      });
  }

  
  defineExpose({
    add,
    edit,
    submitForm,
    addSubProject,
    getQueryByProjectId,
  });
</script>

<style lang="less" scoped>
  .antd-modal-form {
    padding: 14px;
  }
</style>
